import React from 'react';
import { Form, Card, Spin, Table, Typography } from 'antd';
import { get as _get } from 'lodash';
import Step from '@/components/Step';
import { Link }  from 'umi';

import moment from 'moment';
import { getDiffContentData } from '@/pages/Flow/Mine/WaitApproval/gradeFormItem';
import DiffContent from '@/pages/Flow/components/DiffContent';
import { RankTree } from './components';
import { useGradeAndType, useGradeHistory, useGradeTypeHistory, useProcessDetail } from './hooks';
import { FORM_TYPE_MAP } from './utils';
import HistoryDeffContent from './HistoryDeffContent';
import styles from './style.less';

const columns = [
    {
        title: '制度编号',
        dataIndex: 'institutionNo',
        key: 'institutionNo',
        width: 150
    },
    {
        title: '申请日期',
        dataIndex: 'applyDate',
        key: 'applyDate',
        width: 120,
        render: text => `${moment(text).format('YYYY-MM-DD')}`
    },
    {
        title: '生效日期',
        dataIndex: 'startTime',
        key: 'startTime',
        width: 135,
        render: text => `${moment(text).format('YYYY-MM-DD')} 起`
    },
    {
        title: '发布人',
        dataIndex: 'applyEmployeeName',
        key: 'applyEmployeeName',
        width: 80
    },
    {
        title: '审批人',
        dataIndex: 'approveEmployeeName',
        key: 'approveEmployeeName',
        width: 80,
        render: text => (
            <Typography.Text style={{ width: 80, marginBottom: 0 }} title={text} ellipsis>
                {text}
            </Typography.Text>
        )
    },
    {
        title: '原因',
        dataIndex: 'modifyRemark',
        key: 'modifyRemark',
        width: 500,
        render: text => (
            <Typography.Text style={{ width: 500, marginBottom: 0 }} title={text} ellipsis>
                {text}
            </Typography.Text>
        )
    }
];

const method = {
    [FORM_TYPE_MAP[0]]: useGradeTypeHistory,
    [FORM_TYPE_MAP[1]]: useGradeHistory
};

const JobRankHistory = props => {
    const { location } = props;
    const { query } = location;
    const [formType, setFormType] = React.useState(query.type);
    const [selectedCode, setSelectedCode] = React.useState(query.code);
    const [loading, data] = useGradeAndType();
    const [currentRow, setCurrentRow] = React.useState({});

    // 由于后端返回的子节点id 与父节点id 一样，所以需要特殊处理
    const [historyLoading, historyData] = method[formType](selectedCode, formType);

    const [processLoading, process, hasError, isNewWorkFlow] = useProcessDetail(currentRow);

    // 设置默认选中行
    React.useEffect(() => {
        if (historyData.length !== 0) {
            setCurrentRow(historyData[0]);
        } else {
            setCurrentRow(null);
        }
    }, [historyData]);

    const treeData = React.useMemo(
        () =>
            data.map(({ rankTypeCode, rankTypeName = '', postGradeList = [], state }) => ({
                key: `${FORM_TYPE_MAP[0]}-${rankTypeCode}`,
                title: rankTypeName,
                state,
                children: postGradeList.map(({ rankCode, rankName, state: _state }) => ({
                    key: `${FORM_TYPE_MAP[1]}-${rankCode}`,
                    title: rankName,
                    state: _state
                }))
            })),
        [data]
    );
    const handleRowClick = (row = {}) => ({
        onClick() {
            setCurrentRow(row);
        }
    });

    const handleSelect = value => {
        if (!value.length) return;
        const [type, finalValue] = value[0].split('-');
        setFormType(type);
        setSelectedCode(finalValue);
    };

    const defaultKeys = React.useMemo(() => [`${formType}-${selectedCode}`], [formType, selectedCode]);

    const detailLoading = historyLoading || processLoading;
    const diffContent = React.useMemo(() => {
        if (detailLoading) {
            return [];
        }
        const { detail = {} } = process;
        const { formKey = [] } = detail;
        const content = _get(detail, 'formValueJson[1]') || {};
        return getDiffContentData(formKey, content);
    }, [process.detail, detailLoading]);

    return (
        <Card title="历史记录" style={{ margin: '12px 16px 16px 16px' }} bordered={false}>
            <div style={{ display: 'flex' }}>
                <RankTree
                    treeData={treeData}
                    title="职级序列和职级"
                    loading={loading}
                    onSelect={handleSelect}
                    defaultSelectedKeys={defaultKeys}
                />
                <div style={{ flex: 1, marginLeft: 24, overflow: 'hidden' }}>
                    <div className={styles.title}>记录列表</div>
                    <Table
                        className={styles.historyTable}
                        rowKey="id"
                        loading={historyLoading}
                        dataSource={historyData}
                        columns={columns}
                        pagination={false}
                        scroll={{ x: 'max-content' }}
                        style={{ marginBottom: 24 }}
                        onRow={handleRowClick}
                        rowClassName={record => (record.id === currentRow?.id ? 'selectedRow' : '')}
                    />
                    {!hasError && currentRow && (
                        <>
                            <div className={styles.title}>记录详情</div>
                            <Spin spinning={detailLoading}>
                                {!processLoading && isNewWorkFlow === false && currentRow && (
                                    <DiffContent data={diffContent} />
                                )}
                                {!processLoading && isNewWorkFlow === true && currentRow && (
                                    <HistoryDeffContent
                                        type={currentRow.rankCode ? 'OrgRankApply' : 'OrgRankTypeApply'}
                                        process={process}
                                    />
                                )}
                            </Spin>
                            <div className={styles.title} style={{ marginTop: 24 }}>
                                审批流程
                                <div className={styles.subTitle}>
                                    申请主题：
                                    {!processLoading && isNewWorkFlow === false && currentRow && (
                                        <Link
                                            to={{
                                                pathname:
                                                    '/office/institutions/flowManage/fullApprovalProcess/processDetail',
                                                query: {
                                                    actionShow: 'no',
                                                    applicationNo: process.detail.applicationNo
                                                }
                                            }}
                                        >
                                            {process.detail.applicationName}
                                        </Link>
                                    )}
                                    {!processLoading && isNewWorkFlow === true && currentRow && (
                                        <Link
                                            to={{
                                                pathname: '/personal/portal/myAuditRead/myAuditReadDetail',
                                                query: {
                                                    applicationNo:
                                                        process.detail?.formValueMap?.applicationNo ||
                                                        currentRow.applicationNo
                                                }
                                            }}
                                        >
                                            {process.detail.processInstanceName}
                                        </Link>
                                    )}
                                </div>
                            </div>
                            {currentRow && (
                                <Spin spinning={processLoading}>
                                    <Step data={process.step} />
                                </Spin>
                            )}
                        </>
                    )}
                </div>
            </div>
        </Card>
    );
};

export default Form.create({ name: 'JobRankHistory' })(JobRankHistory);
